<?php


namespace apps\marriage\app\mp\controller;


use apps\marriage\core\service\MemberProfileService;
use apps\marriage\core\service\MemberVisitService;
use apps\marriage\core\service\UserService;
use think\Exception;
use think\Request;

class VisitorController extends BaseMarriageMpController
{
    /**
     * @var MemberVisitService
     */
    private $memberVisitorService;

    /**
     * @var MemberProfileService
     */
    private $memberProfileService;

    /**
     * @var UserService
     */
    private $userService;

    protected function init()
    {
        parent::init();
        $this->memberVisitorService = service('MemberVisit', SERVICE_NAMESPACE);
        $this->memberProfileService = service('MemberProfile', SERVICE_NAMESPACE);
        $this->userService = service('User', SERVICE_NAMESPACE);
    }

    public function lists(Request $request)
    {
        $pageSize = $request->param('page_size', 10);
        $type = $request->param('type', 'my');
        $params = [];
        if($type == 'my') {
            $params['user_id'] = $this->user['id'];
        } else if($type == 'others') {
            $rights = $this->memberProfileService->getVipRightsByUserId($this->user['id']);
            if(!$rights['view_visitor_enable']) {
                throw new Exception('您当前无权限查看访客记录，请开通VIP');
            }

            $myMember = $this->memberProfileService->getByUserId($this->user['id']);
            $params['member_profile_id'] = $myMember['id'];
        } else {
            throw new Exception('参数错误');
        }
        $res = $this->memberVisitorService->pageListByParams($params, $pageSize);
        if($res['data']) {
            $dataList = [];
            foreach ($res['data'] as $rs) {
                $member = $this->memberProfileService->getByPk($rs['member_profile_id']);
                $user = $this->userService->getByPk($member['user_id']);
                $user = arrayOnly($user, ['id', 'nick', 'avatar_url']);
                $dataList[] = [
                    'member' => $this->memberProfileService->format($member),
                    'user' => $user
                ];
            }
            $res['data'] = $dataList;
        }
        return $this->success($res);
    }
}